<template>
    <div>
        <Modal v-model="isVisible"
	        title="人员出入异常"
	        width="1200"
	        :mask-closable="false"
	        @on-visible-change="onVisibleChange">

	        <div class="search" @keydown.enter="search">
	        	<div class="search-label">城市</div>
                <city-code-selector v-model="searchForm.regionCode" style="width: 120px;"></city-code-selector>

                <span class="search-label">人员标签</span>
                <Select v-model="searchForm.tagId" style="width: 100px">
	                <Option v-for="type in tags" :key="type.id" :value="type.id">{{type.name}}</Option>
	            </Select>

                <span class="search-label">预警人</span>
                <Input v-model="searchForm.people" placeholder="姓名/手机号码" style="width: 200px;"></Input>

                <span class="search-label">房源地址</span>
                <Input v-model="searchForm.address" placeholder="房源地址/房源编号" style="width: 200px;"></Input>

               	<Button @click="loadData" class="search-btn" type="primary">搜索</Button>
		    </div>
            
            <Table stripe border :columns="columns" :data="datas"></Table>

            <div slot="footer">
            </div>
            
        </Modal>

        <member-detail
            :visible.sync="memberDetail.visible"
            :user-id="memberDetail.userId"
            :role-id="memberDetail.roleId">
        </member-detail>
    </div>
</template>

<script type="text/javascript">
import debounce from 'lodash/debounce'
import util from '@/libs/util'
import { dayjs, date } from '@/libs/date'
import { http, api } from '@/libs/http'
import cityCodeSelector from '@/components/city-code-selector'
import memberDetail from '@/components/member-detail'

export default {
  name: 'leave-enter-abnormal-modal',
  components: {
    cityCodeSelector,
    memberDetail
  },
  props: {
    visible: {
      type: Boolean
    }
  },
  data () {
    return {
      tags: [{
        id: 0,
        name: '不限'
      }],
      searchForm: {
        regionCode: 0,
        tagId: 0,
        people: '',
        address: ''
      },
      columns: [
        {
          title: '预警人',
          render: (h, { row }) => {
            return <a href='javascript:;' onClick={() => this.handleMemberDetail(row)}>[{row.tenant_tag.name}]{row.name}</a>
          }
        },
        { title: '房源所在城市', render: (h, p) => <span>{p.row.home.city} {p.row.home.district}</span> },
        { title: '房源编号', render: (h, p) => <span>{p.row.home.home_name}</span> },
        { title: '房源地址', render: (h, p) => <span>{p.row.home.detail_address}</span> },
        { title: '预警原因', render: (h, p) => <span>{this.getReason(p.row.last_open_access_time)}</span> },
        { title: '最后一次开门时间', render: (h, p) => <span>{date(p.row.last_open_access_time)}</span> },
        {
          title: '操作',
          render: (h, p) => {
            return (
              <div>
                <i-button onClick={() => this.confirmDel(p.row)}>解除预警</i-button>
              </div>
            )
          }
        }
      ],
      datas: [],
      memberDetail: {
        userId: 0,
        roleId: 2,
        visible: false
      }
    }
  },

  computed: {
    isVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('on-close', val)
      }
    },
    cities () {
      return this.$store.state.ticket.allCities
    }
  },

  mounted () {
    this.loadTenantTags()
  },

  // watch: {
  //     searchForm: {
  //         deep: true,
  //         handler() {
  //             const { city } = this.searchForm;

  //             util.log(city);

  //             // if (rest.city) data.cityName = this.cities.find(city => city.region_code === rest.city).name;

  //             // this.$emit('update:model', util.cleanObj(data));
  //         }
  //     }
  // },

  methods: {
    onVisibleChange (v) {
      if (v) {
        this.datas = []
        this.reset()
        this.loadData()
      } else {
        this.leased = false
      }
    },

    // 重置
    reset () {
      this.searchForm = {
        regionCode: 0,
        tagId: 0,
        people: '',
        address: ''
      }
    },

    // 获取租客标签
    async loadTenantTags () {
      try {
        const res = await http.req(api.tenant_tags_get)
        if (res && res.rows && res.rows.length) {
          this.tags = this.tags.concat(res.rows)
        }
      } catch (err) {
        util.log('loadTenantTags:', err)
      }
    },

    // 加载数据
    async loadData () {
      try {
        const { regionCode, tagId, people, address } = this.searchForm

        const params = {
          region_code: regionCode || null,
          tenant_tag_id: tagId || null,
          name: people || null,
          phone: people || null,
          home_address: address || null,
          home_name: address || null
        }

        const res = await http.req(api.face_access_get_exception_tenants, null, params)
        if (res && res.rows) {
          this.datas = res.rows
          this.$emit('on-update', res.count)
        }
      } catch (err) {
        console.log(err)
      }
    },

    // 返回原因
    getReason (lastOpenTime) {
      let diff = dayjs().valueOf() - dayjs(lastOpenTime).valueOf()
      diff = Math.floor(diff / (24 * 60 * 60 * 1000))
      return '超过' + diff + '天没有开门记录'
    },

    // 选择城市
    handleFetchCities: debounce(function (keyword) {
      if (/^\s+/.test(keyword)) return
      this.fetchCities(keyword)
    }, 300),

    async fetchCities (name) {
      this.cities = await http.req(api.address_cities, null, { name })
    },

    // 显示人员信息
    async handleMemberDetail (record) {
      this.memberDetail.userId = record.id
      this.memberDetail.visible = true
    },

    // 确定解除
    confirmDel (item) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定解除预警？',
        onOk: () => {
          this.delLeaveEnterAbnormal(item)
        }
      })
    },

    // 解除预警
    async delLeaveEnterAbnormal (item) {
      try {
        const params = {
          tenant_id: item.id,
          home_id: item.home.id
        }

        const res = await http.req(api.face_access_del_exception_tenants, null, params)

        if (res) {
          this.loadData()
          this.$Message.success('解除成功')
        }
      } catch (err) {
        util.log('delLeaveEnterAbnormal:', err)
      }
    }
  }
}
</script>

<style lang='less'>
.search {
	display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
}
.search-label {
	padding: 0 5px;
}
</style>